var appMakersManager;

function Category () {
    this.id = new Number()
    this.markers = new Array ();
    this.texto = new String ();
    this.categoria = new String ();
}

var controls = {
    categoryListContainer: document.createElement('div'),
    detailsContainer: document.createElement('div'),
    buscadorContainer:{}
};

//BUSCADOR MAPA
function BuscadorMapa () {
    this.map = {},
    this.geocoder = new google.maps.Geocoder(),
    this.southWest = new google.maps.LatLng(-17.895114,-81.650391),
    this.northEast = new google.maps.LatLng(0.175781,-68.554688),
    this.latLngBounds = new google.maps.LatLngBounds(new google.maps.LatLng(-17.895114,-81.650391),new google.maps.LatLng(0.175781,-68.554688)),
    this.createComponent = function () {
        var self = this;
        var $div = $('<div></div>');
        var $input = $('\
                <input \
                    id="mapa-search-input"\
                    class="input-medium ui-autocomplete-input" \
                    size="16" type="text" placeholder="&iquest;D&oacute;nde est&aacute;s?" \
                    style="height: 32px; padding: 0 6px 0; margin: 6px 0" \
                    autocomplete="off" \
                    role="textbox" \
                    aria-autocomplete="list" \
                    aria-haspopup="true">\
                </input>\
        ');
        var $btnBuscar = $('<a id="bnt-buscar" class="btn btn-green" style="margin-top: 6px; height: 24px; position: absolute;"><i class="fa fa-search" style="margin-top: 4px;"></i></a>');
        $input.bind('keypress', function(e) {
            if(e.keyCode==13){
                e.preventDefault();
                if ($("#mapa-search-input").val()) {
                    self.buscar();
                }
            }
        });
        $btnBuscar.click(function () {
            if ($("#mapa-search-input").val()) {
                self.buscar();
            }
        })
        $input.appendTo($div);
        $btnBuscar.appendTo($div);
        controls.buscadorContainer = $div.get(0);
    }
    this.buscar = function () {
        var direccion = $('#mapa-search-input').val();
        $('#mapa-search-input').val('');
        $('#mapa-search-input').autocomplete('close');
        this.processGeocoding(direccion, this.centrarMapa);
    }

    this.processGeocoding = function (location, callback) {
        var self = this;
        var request = {
            language: 'es',
            region: 'PE',
            address: location + ' Peru'
        }
        this.geocoder.geocode(request, function(results, status) {
            if(status == google.maps.GeocoderStatus.OK) {
                self.centrarMapa (results);
                return results;
            }
            return status;
        });
    }

    this.centrarMapa = function (geocodes) {
        this.map.setZoom(13);
        this.map.setCenter(geocodes[0].geometry.location);
    }

    this.init = function (map) {
        this.map = map;
        this.createComponent();
    }
}
//FIN BUSCADOR MAPA

//AUTOCOMPLETE
function Predictivo () {
    this.init = function (map) {
        var geocoder = new google.maps.Geocoder();
        var latLngBounds = new google.maps.LatLngBounds(new google.maps.LatLng(-17.895114,-81.650391),new google.maps.LatLng(0.175781,-68.554688));
        $('#mapa-search-input').autocomplete({
            source: function(request, response){
                geocoder.geocode({
                    address: request.term + ' Peru',
                    region: 'PE',
                    bounds: latLngBounds
                }, function(results, status){
                    response($.map(results, function(item){
                        return {
                            label: item.formatted_address,
                            value: item.formatted_address,
                            latitude: item.geometry.location.lat(),
                            longitude: item.geometry.location.lng()
                        }
                    }));
                })
            },
            select: function(event, ui){
                var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
                map.setCenter(location);
                map.setZoom(13);
                //marker = new google.maps.Marker({
                   // map: mapaController.map.defs.map,
                    //position: location
                //});
            }
        });
    }
}
//FIN AUTOCOMPLETE

function Categories () {
    this.isLoad = false;
    this.list = {};
    this.ids = {};
    this.load = function () {
	var self = this;
	$.ajax({
	    url: BASE_URL+'php/controllers/categoria.controller.php',
	    success: function (data) {
                console.log(data)
		var cat = {}, i;
                for (var n=0, l=INIT.length; n<l; n++) {
                    i = INIT[n];
                    cat = new Category ();
		    cat.id = data['categorias'][i]['id'];
		    cat.texto = data['categorias'][i]['nombre'];
		    cat.categoria = data['categorias'][i]['identificador'];
		    self.list[data['categorias'][i]['id']] = cat;
                    self.ids[data['categorias'][i]['identificador']] = data['categorias'][i]['id'];
                }
		self.isLoad = true;
		$(document).ready(function () {
		    appMap = new MapController();
		    appMap.init();
                    var wh = $(window).height();
                    $('#mapa-content, #mapa-page').css({height:wh, 'min-height':wh});
                    var appPredictivo = new Predictivo();
                    setTimeout(function () {
                        appPredictivo.init(appMap.map)
                    },500)
		})
	    }
	})
    }
}

var appCategories = new Categories();
appCategories.load();

//MAP CONTROLLER
function MapController () {
    var self = this;
    this.map = null;
    this.defs = {
	center: new google.maps.LatLng(-12.047379,-77.061882),
	container:'mapa-content',
        urlMarker:false
    }
    this.options = {
	zoom: 13,
	mapTypeId: google.maps.MapTypeId.ROADMAP,
	disableDefaultUI: true,
	zoomControl: true,
	zoomControlOptions: {
	    style: google.maps.ZoomControlStyle.SMALL
	}
    }
    this.dynamicUrlParser = function () {
        var url = window.parent.document.location+'', id = 0;
        url = url.replace(PARENT_BASE_URL+'mapa', '')
        .replace('#!/', '')
        .replace(/^\//, '')
        .replace(/\/$/, '');

        if (url.indexOf('recicladora/') != -1) {
            var params = '';
            self.defs.urlMarker = true;
            url = url.replace('recicladora/', '');
            params = url.split('/');
            document.getElementById('markerId').value = params[2];
            $.ajax({
                type:'POST',
                data: 'id='+params[2],
                url:BASE_URL+'php/controllers/findMarker.controller.php',
                success:function (data) {
                    var idCategoria = appCategories.ids[params[1]];
                    appMap.map.panTo(new google.maps.LatLng(data.latitud, data.longitud));
                    appMakersManager.load(idCategoria, params[2]);
                    //self.cargarXML(idCategoria, params[2]);
                    $('#categoria'+idCategoria).addClass('active');
                    //mapaController.getContent.check(idCategoria)
                }
            })
        } else {
            var categorias = url.split('/');
            if (!!categorias[0]) {
                for (var i in categorias) {
                    id = appCategories.ids[categorias[i]]
                    appMakersManager.load(id);
                    $('#categoria'+id).addClass('active');
                }
            }

        }
    }
    this.init = function () {
	this.map = new google.maps.Map(document.getElementById(this.defs.container), this.options);
	this.map.setCenter(this.defs.center);

	GT_Geolocation.localize(this.map);
	var appSliderBox = new SliderBox();
	appSliderBox.create();

        var buscadorMapaInstance = new BuscadorMapa();
        buscadorMapaInstance.init(this.map);

	controls.categoryListContainer.index = -500;
	//controls.detailsContainer.index = -500;

	this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(controls.categoryListContainer);
	this.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controls.detailsContainer);
        this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(controls.buscadorContainer);

	appMakersManager = new MarkersManager (appSliderBox, this.map);
        setTimeout(this.dynamicUrlParser, 500)
        //this.dynamicUrlParser();
    }
}
//FIN MAP CONTROLLER

//MARKERS MANAGER
function MarkersManager (appSliderBox, map) {
    this.map = map
    this.defs = {
	infomarkerTpl: document.getElementById('infomarkerTpl').value,
	detailsContaier: false
    }
    this.load = function (catgoriaId, markerId) {
	var self = this;
	var appInfobox = new InfoboxManager();
	$.ajax({
	    type:'GET',
	    data: 'categoriaId='+catgoriaId,
	    url:BASE_URL+'php/controllers/marker.controller.php',
	    success:function (xml) {
		var punto;
		$(xml).find('marker').each(function() {
		    punto = new google.maps.LatLng(
			parseFloat($(this).attr("lat")),
			parseFloat($(this).attr("lng"))
			);
		    var marker = new google.maps.Marker({
			map: appMap.map,
			position: punto,
			icon: POINTS_IMAGES+$(this).attr('imagen')+'.png',
			shadow: POINTS_IMAGES+'sombra.png',
			id:$(this).attr('id'),
			nombreUrl: $(this).attr('nombreUrl'),
			nombre: $(this).attr('nombre'),
			direccion: $(this).attr('direccion'),
			imagen: $(this).attr('imagen'),
			categoriasToString: $(this).attr('categoriasToString')
		    });
		    appCategories.list[catgoriaId].markers[$(this).attr('id')] = marker;
		    appInfobox.bindMarker(appMap.map, marker);
		    self.bindMarker(marker);
		})
                if (markerId != undefined) {
                    marker = appCategories.list[catgoriaId].markers[markerId];
                    marker.infobox.open(appMap.map, marker);
                    appInfobox.currentInfobox = marker.infobox;
                    self.mostrarDetalles(marker);
                    appSliderBox.moving(controls.detailsContainer, 'det');
                }
		punto = null;
	    }
	})
    }
    this.mostrarMarkers = function (categoriaId) {
	var self = this;
	if (appCategories.list[categoriaId].markers.length) {
	    for (n in appCategories.list[categoriaId].markers) {
		appCategories.list[categoriaId].markers[n].setMap(appMap.map);
	    }
	} else {
	    self.load(categoriaId);
	}
    }
    this.ocultarMarkers = function (categoriaId) {
	if (appCategories.list[categoriaId].markers.length) {
	    for (n in appCategories.list[categoriaId].markers) {
		appCategories.list[categoriaId].markers[n].setMap(null);
	    }
	} else {
	    self.load(categoriaId);
	}
    },
    this.mostrarDetalles = function (marker) {
	var self = this;
	/*if (!self.defs.detailsContaier) {
	    self.defs.detailsContaier = document.getElementById('marker-details-content');
	}*/
	$.ajax({
	    url:BASE_URL+'php/controllers/infomarker.controller.php?id='+marker.id,
	    data:{
		id:marker.id
	    },
	    type:'post',
	    beforeSend:function () {
		controls.detailsContainer.innerHTML = '\
                    <div class="medium-loader" style="width:100%; min-height:'+$(window).height()+'px">\
                        <div class="circle-container rad-border">\
                            <div class="circle-loader rad-border"></div>\
                            <div class="circle-content rad-border"></div>\
                            <div class="center-circle-image rad-border"></div>\
                        </div>\
                    </div>\
                ';
	    },
	    success:function (data) {
		var tpl = self.defs.infomarkerTpl.replace('${classyCategories}', self.classyCategories(data.categoriasToIds));
		var replacer = new Replacer();
		var html = replacer.itemReplace(tpl, data);
		controls.detailsContainer.innerHTML = html;
		appSliderBox.scrollEvents('marker-details-content');
                if (data.direccion == "") $('#address-item').remove();
                if (data.horario == "") $('#hour-item').remove();
                if (data.telefono == "") $('#phone-item').remove();
                if (data.email == "") $('#email-item').remove();
                if (data.quienes == "") $('#quienes-item').remove();
                if (data.que == "") $('#que-item').remove();
                if (data.porque == "") $('#porque-item').remove();
                if (data.comentario == "") $('#description-item').remove();                
	    }
	})
    }
    this.bindMarker = function (marker) {
	var self = this;
	google.maps.event.addListener(marker, 'click', function() {
	    if (!$('#marker-details-content').hasClass('active')) {
		appSliderBox.moving(controls.detailsContainer, 'det');
	    }
	    self.mostrarDetalles(marker);
            self.changeUrlBymarker(marker);
            this.map.setZoom(13);
            this.map.setCenter(marker.getPosition());
	})
    }
    this.changeUrlBymarker = function (marker) {
        var hash = marker.nombreUrl+'/'+marker.imagen+'/'+marker.id;
        if (navigator.appName == "Microsoft Internet Explorer") {//si es explorer
            if (window.partent.location.href.indexOf('#') == -1) {
                window.partent.document.location = PARENT_BASE_URL+'mapa/#!/recicladora/'+hash;
            } else {
                window.partent.document.location.hash = '#!/recicladora/'+hash;
            }
        } else {//si es otro navegador
            window.parent.history.replaceState('', marker.nombre, PARENT_BASE_URL+'mapa/recicladora/'+hash);
        }
    }
    this.classyCategories = function (c) {
	c = c.split(',');
	var html = '';
	for (var i=0, l=c.length; i<l; i++) {
            if (INIT.indexOf(c[i]*1) != -1) {
                html += '<em class="recive-item '+appCategories.list[c[i]].categoria+'-item"><span class="bg-color"></span><span class="val">'+appCategories.list[c[i]].texto+'</span></em>';
            }
	}
	return html;
    }
}
//FIN MARKERS MANAGER
$(window).resize( function () {
    if ($(window).width() > 767) {
    controls.categoryListContainer.className = 'category-list-container border-left overflow active';
    }else{
    controls.categoryListContainer.className = 'category-list-container border-left overflow';
    }
    if ($(window).width() > 767) {
    controls.categoryListContainer.style.marginLeft = '0px';
    }else{
    controls.categoryListContainer.style.marginLeft = '-200px'; 
    }
});

//SLIDER BOX
function SliderBox () {
    this.defs = {
        btn: document.createElement('input'),
        btnDetails: document.createElement('input'),
        isOpen: true
    }
    this.create = function () {
        controls.categoryListContainer.id = 'category-list-container';
        if ($(window).width() > 767) {
            controls.categoryListContainer.className = 'category-list-container border-left overflow active';
        }else{
            controls.categoryListContainer.className = 'category-list-container border-left overflow';
        }
        if ($(window).width() > 767) {
            controls.categoryListContainer.style.marginLeft = '0px';
        }else{
            controls.categoryListContainer.style.marginLeft = '-200px'; 
        }
        controls.categoryListContainer.style.height = $(window).height()+'px';
        controls.categoryListContainer.innerHTML = '\
            <div class="scrollear">\
            <div class="category-list-title">\
                <h4>Eleg&iacute; qu&eacute <b>reciclar</b></h4>\
            </div>\
                <span class="border-width bg-color-07"></span>\
                <ul id="category-list" class="category-list box-list first-level">'+this.createItems()+'</ul>\
            </div>\
        ';

        //BOTON ABRIR Y CERRAR CATEGORIAS//
        this.defs.btn.id = 'btn-expand-markers-list';
        this.defs.btn.type = 'button';
        controls.categoryListContainer.appendChild(this.defs.btn);

        //FIN BOTON ABRIR Y CERRAR CATEGORIAS//
    
    
        controls.detailsContainer.id = 'marker-details-content';
    
        controls.detailsContainer.className = 'overflow';
        controls.detailsContainer.innerHTML = '\
            <div class="scrollear">\n\
                <div class="content">\
                    <div id="datos-row" class="span">\
                        <h5 class="info-title">Hac&eacute; click en un punto en el mapa para ver m&aacutes informaci&oacute;n</h5>\
                    </div>\
                </div>\
            </div>';

        this.defs.btnDetails.id = 'btn-expand-markers-details';
        this.defs.btnDetails.type = 'button';
        controls.detailsContainer.appendChild(this.defs.btnDetails);
        controls.detailsContainer.style.height = $(window).height()+'px';
        if ($(window).width() < 767) {
            controls.detailsContainer.style.width = ($(window).width()-30)+'px';
            controls.detailsContainer.style.marginRight = (60-$(window).width())+'px';  
        } else {
            controls.detailsContainer.style.width = '420px';
            controls.detailsContainer.style.marginRight = '-410px';
        }

        this.bind();
    }
    this.bind = function () {
        var self = this;

        //BOTON CERRAR ACTION//
        $('#btn-expand-markers-list').live('click', function(){
            self.moving(controls.categoryListContainer, 'cat');
        });
        $('#btn-expand-markers-details').live('click', function(){
            self.moving(controls.detailsContainer, 'det');
        });
        /*if($(window).width() < 767) {
	    $(controls.categoryListContainer).find('a').live('click', function(){
		self.moving(controls.categoryListContainer, 'cat');
	    });
	    $(controls.detailsContainer).find('a').live('click', function(){
		self.moving(controls.detailsContainer, 'det');
	    });
	}*/
        self.scrollEvents('category-list-container');
    }
    this.moving = function (el, what){
        var move, obj;
        el = $(el);
        if (what == 'det') {
            move = (window.innerWidth < 767) ? $(window).width()-60 : 410;
            obj = {
                'marginRight': move
            };
        } else {
            move = (window.innerWidth < 767) ? ($('#category-list-container').width()-$('#btn-expand-markers-list', '#category-list-container').outerWidth(true)) : 141;
            obj = {
                'marginLeft': move
            };
        }
        if (!el.hasClass('active')) {
            el.addClass('active');
            move = '+=' + move + 'px';
        } else {
            el.removeClass('active');
            move = '-=' + move + 'px';
        }
        if (what == 'det') {
            obj = {
                'marginRight': move
            };
        } else {
            obj = {
                'marginLeft': move
            };
        }
        el.animate(obj, {
            duration: 500,
            step: function() {
                google.maps.event.trigger(appMap.map, 'resize');
            }
        });
    }
    this.scrollEvents = function (container){
        var self = this
        if (!!$('#' + container + '.overflow').length) {
            var myScroll;
            function loaded() {
                myScroll = new iScroll(container);
                if (!!myScroll.vScrollbarWrapper) {
                    myScroll.vScrollbarWrapper.setAttribute('class', 'scrollbar');
                }
            }
            /*document.addEventListener('touchmove', function (e) {
		e.preventDefault();
	    }, false);*/
            if(getInternetExplorerVersion() != '-1' && getInternetExplorerVersion() <= '8') {
                document.attachEvent('touchmove,', function (e) {
                    e.preventDefault();
                }, false);
                document.attachEvent('DOMContentLoaded', loaded, false);
            } 

            else {
                document.addEventListener('touchmove', function (e) {
                    e.preventDefault();
                }, false);
                document.addEventListener('DOMContentLoaded', loaded, false);
            }
            loaded();
        } else {
            setTimeout(function () {
                self.scrollEvents(container)
            }, 1000)
        }
    },
    this.createItems = function () {
        var btns = '', active = '', i;
        ///for (var i in appCategories.list) {
        for (var n=0, l=INIT.length; n<l; n++) {
            i = INIT[n];
            active = (!n)?' active':'';
            btns += '\
                    <li class="list-item '+appCategories.list[i]['categoria']+'-item">\
                        <span class="border-width bg-color-'+appCategories.list[i]['categoria']+'"></span>\
                        <a class="link" href="'+appCategories.list[i]['categoria']+'" title="Puntos de reciclado de '+appCategories.list[i]['texto']+'" id="categoria'+appCategories.list[i]['id']+'" onclick="bindItem(this);return false;">\
                            <span class="text">'+appCategories.list[i]['texto']+'</span>\
                        </a>\
                    </li>\
                ';
        }
        return btns;
    }
}
//FIN SLIDER BOX

//INFOBOX
function InfoboxManager () {
    this.defs = {
	tpl:document.getElementById('infoboxContent'),
        currentInfobox:{}
    }
    this.options = {
	content: '',
	disableAutoPan: true,
	maxWidth: 0,
	pixelOffset: new google.maps.Size(15, -60),
	zIndex: null,
	closeBoxURL: '',
	infoBoxClearance: new google.maps.Size(1, 1),
	isHidden: false,
	pane: 'floatPane',
	enableEventPropagation: false
    }
    this.createInfoboxHtml = function (marker) {
	var content = this.defs.tpl.value.replace(/\$\{markerNombre\}/g, marker.nombre)
	.replace(/\$\{markerDireccion\}/g, marker.direccion)
	.replace(/\$\{markerImagen\}/g, marker.imagen)
	.replace(/\$\{categoriasToString\}/g, marker.categoriasToString)
	.replace(/\$\{[a-zA-Z]+\}/g, '')
	;
	var container = document.createElement('div');
	container.className = 'infobox';
	var target = document.createElement('div');
	target.className = 'target';
	container.innerHTML = content;
	container.appendChild(target);
	return {
	    container:container,
	    target:target
	}
    },
    this.bindMarker = function (mapa, marker) {
	var self = this;
	var infobox = new InfoBox(self.options);
	var infoboxHtml = self.createInfoboxHtml(marker);
	infobox.setContent(infoboxHtml.container);
	marker.infobox = infobox;
	google.maps.event.addListener(marker, "mouseover", function (e) {
	    if (self.currentInfobox != undefined) {
                self.currentInfobox.close();
            }
	    marker.infobox.open(mapa, marker);
	    self.currentInfobox = marker.infobox;
	})
	google.maps.event.addListener(marker, "mouseout", function (e) {
	    marker.infobox.close()
	});
    }
}

function bindItem (self) {
    if ($(self).hasClass('active')) {
	$(self).removeClass('active');
    } else {
	$(self).addClass('active');
    }
    if ($(self).hasClass('active')) {
	appMakersManager.mostrarMarkers($(self).attr('id').slice(9));
    } else {
	appMakersManager.ocultarMarkers($(self).attr('id').slice(9));
    }
}

var resizeWindow = function(){
    var w = $(window), ww, wh, b = $('body');

    w.resize(function(){
	mqClass();
        wh = $(window).height();
        $('#category-list-container, #mapa-content, #marker-details-content, #mapa-page').css({height:wh, 'min-height':wh})
    });

    function mqClass(){
	ww = $(window).width();

	if (ww <= 480) {
	    b.addClass('mq1200 mq979 mq767 mq480');
	} else if (ww <= 767) {
	    b.removeClass('mq480').addClass('mq1200 mq979 mq767');
	} else if (ww <= 979) {
	    b.removeClass('mq767 mq480').addClass('mq1200 mq979');
	} else if (ww <= 1200) {
	    b.removeClass('mq979 mq767 mq480').addClass('mq1200');
	}
    }
    mqClass();
};

window.onload = function () {
    resizeWindow();
}

function getInternetExplorerVersion() {
   var rv = -1;
   if (navigator.appName == 'Microsoft Internet Explorer')
   {
      var ua = navigator.userAgent;
      var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
      if (re.exec(ua) != null)
         rv = parseFloat( RegExp.$1 );
   }
   return rv;
}